package cn.kooki.app.duobao.ui.Activity.User;

import android.text.TextUtils;
import android.view.View;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.UserRefrshEvent;
import cn.kooki.app.duobao.ui.widget.ClearEditText;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/12/29.
 */
public class UpdateNickNameActivity extends BaseNavActivity implements View.OnClickListener {
    @Bind(R.id.et_nickname)
    ClearEditText etNickname;
    private UserInfo userinfo;

    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_profile_nickame);
        ButterKnife.bind(this);
    }

    @Override
    protected void afterView() {
        setTitle(R.string.title_activity_nickname_edit);
        actionEdit.setText(R.string.save);
        actionEdit.setTextColor(getResources().getColor(R.color.blue));
        actionEdit.setVisibility(View.VISIBLE);
        actionEdit.setOnClickListener(this);
        userinfo = SharePreferencesUtils.getUserinfo(this);
        etNickname.setText(userinfo.getUsername());
    }


    @Override
    public void onClick(View v) {
        if (v == actionEdit) {
            if (TextUtils.isEmpty(etNickname.getText().toString())) {
                showToastMessage("请输入昵称");
            } else {
                upload();
            }
        }
    }

    private void upload() {
        if (etNickname.getText().toString().equals(userinfo.getUsername())) {
            return;
        } else {
            showLoading("正在修改..");
            MainFactory.getApiInstance().modeNick(etNickname.getText().toString(), userinfo.getUid(), new Callback<BaseResponse>() {
                @Override
                public void success(BaseResponse baseResponse, Response response) {
                    dismissLoading();
                    if (baseResponse.getStatus() == 0) {
                        userinfo.setUsername(etNickname.getText().toString());
                        SharePreferencesUtils.putUserinfo(UpdateNickNameActivity.this, userinfo);
                        EventBus.getDefault().post(new UserRefrshEvent());
                        showToastMessage("修改成功");
                        finish();
                    }else {
                        showToastMessage("修改失败");
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    dismissLoading();
                }
            });
        }
    }
}
